﻿using Coldairarrow.Entity.Base_Company;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.AspNetCore.Hosting;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_Company
{
    public class Base_ComapnyBusiness : BaseBusiness<Base_Comapny>, IBase_ComapnyBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        private readonly IHostingEnvironment _hostingEnvironment;
        public Base_ComapnyBusiness(IDbAccessor db, IHostingEnvironment hostingEnvironment, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
            _hostingEnvironment = hostingEnvironment;
        }

        #region 外部接口

        public async Task<PageResult<Base_Comapny>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_Comapny>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_Comapny, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            return await q.Where(where).GetPageResultAsync(input);
        }

      
        /// <summary>
        /// 获取站点名称信息
        /// </summary>
        /// <returns></returns>
        public List<object> GetCompanyList()
        {
            var list = from a in GetIQueryable().Where(x => !x.Deleted)
                       select new
                       {
                           a.Id,
                           a.Name
                       };
            var res = list.ToList<object>();

            return res;
        }

      

       
        /// <summary>
        /// 获取站点基本信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public CompanyUnitInfo GetTheModel(string id)
        {
            var tModel = GetEntity(id);

            CompanyUnitInfo Model = new CompanyUnitInfo();
            Model.Id = tModel.Id;
            Model.Name = tModel.Name;
            Model.Code = tModel.Code;
            Model.LogoImgPath = tModel.LogoImgPath;
            Model.ResPhone = tModel.ResPhone;
            Model.ResUser = tModel.ResUser;
            Model.HaveMember = tModel.HaveMember;
            Model.LoginType = tModel.LoginType;
            Model.IndexTemplateId = tModel.IndexTemplateId;
            Model.ListTemplateId = tModel.ListTemplateId;
            Model.ShowListTemplateId = tModel.ShowListTemplateId;
            Model.KeepOne = tModel.KeepOne;
            Model.KeepTwo = tModel.KeepTwo;
            Model.KeepThree = tModel.KeepThree;
            Model.KeepFour = tModel.KeepFour;
            Model.SmsAccount = tModel.SmsAccount;
            Model.SmsPassword = tModel.SmsPassword;
            Model.SmsWebSite = tModel.SmsWebSite;

            return Model;
        }

        
        /// <summary>
        /// 获取站点所有信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Base_Comapny GetTheData(string id) 
        {
            return GetEntity(id);
        }
        #endregion

        #region//操作

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddDataAsync(Base_Comapny data)
        {
            var q = GetIQueryable();
            var list = q.Where(x => (x.Name == data.Name) && x.Deleted == false).ToList();
            if (list.Count > 0)
            {
                throw new BusException("子站名称重复请重新输入！");
            }
            else
            {
                await InsertAsync(data);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task UpdateDataAsync(Base_Comapny data)
        {
            var q = GetIQueryable();
            var list = q.Where(x => (x.Name == data.Name) && x.Deleted == false && x.Id != data.Id).ToList();
            if (list.Count > 0)
            {
                throw new BusException("子站名称不能与其他子站重复请重新输入！");
            }
            else
            {

                await UpdateAsync(data);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task DeleteDataAsync(List<string> ids)
        {
            await Db.DeleteAsync<Base_ComapnyData>(x => ids.Contains(x.CompanyId));
            await DeleteAsync(ids);
        }

        #endregion

       
        #region 私有成员
        /// <summary>
        /// 递归拷贝所有子目录。
        /// </summary>
        /// <param >源目录</param>
        /// <param >目的目录</param>
        private static void CopyDirectory(string sPath, string dPath)
        {
            string[] directories = System.IO.Directory.GetDirectories(sPath);
            Log.Information("复制文件夹内容 directories.length = {a}", directories.Length);
            if (!System.IO.Directory.Exists(dPath))
                System.IO.Directory.CreateDirectory(dPath);
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(sPath);
            System.IO.DirectoryInfo[] dirs = dir.GetDirectories();
            CopyFile(dir, dPath);
            if (dirs.Length > 0)
            {
                foreach (System.IO.DirectoryInfo temDirectoryInfo in dirs)
                {
                    string sourceDirectoryFullName = temDirectoryInfo.FullName;
                    string destDirectoryFullName = sourceDirectoryFullName.Replace(sPath, dPath);
                    if (!System.IO.Directory.Exists(destDirectoryFullName))
                    {
                        System.IO.Directory.CreateDirectory(destDirectoryFullName);
                    }
                    CopyFile(temDirectoryInfo, destDirectoryFullName);
                    CopyDirectory(sourceDirectoryFullName, destDirectoryFullName);
                }
            }

        }

        /// <summary>
        /// 拷贝目录下的所有文件到目的目录。
        /// </summary>
        /// <param >源路径</param>
        /// <param >目的路径</param>
        private static void CopyFile(System.IO.DirectoryInfo path, string desPath)
        {
            string sourcePath = path.FullName;
            System.IO.FileInfo[] files = path.GetFiles();
            foreach (System.IO.FileInfo file in files)
            {
                string sourceFileFullName = file.FullName;
                string destFileFullName = sourceFileFullName.Replace(sourcePath, desPath);
                file.CopyTo(destFileFullName, true);
            }
        }

        public Task<Base_Comapny> GetTheDataAsync(string id)
        {
            throw new NotImplementedException();
        }

        public string GetIPath(string id, string wName)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}